﻿using System;
using System.Collections.Generic;

namespace ComponentSystem
{
    /// <summary>
    /// 组件对象池
    /// </summary>
    public class ComponentObjectPool
    {
        /// <summary>
        /// 字典
        /// </summary>
        private readonly Dictionary<Type, Queue<Component>> dictionary = new Dictionary<Type, Queue<Component>>();

        /// <summary>
        /// 获取组件
        /// </summary>
        public Component Fetch(Type type)
        {
            Queue<Component> queue;
            if (!this.dictionary.TryGetValue(type, out queue))
            {
                queue = new Queue<Component>();
                this.dictionary.Add(type, queue);
            }
            Component obj;
            if (queue.Count > 0)
            {
                obj = queue.Dequeue();
            }
            else
            {
                obj = (Component)Activator.CreateInstance(type);
            }
            //obj.IsFromPool = true;
            return obj;
        }

        /// <summary>
        /// 获取组件 -- 泛型模式
        /// </summary>
        public T Fetch<T>() where T : Component
        {
            T t = (T)this.Fetch(typeof(T));
            return t;
        }

        /// <summary>
        /// 检测组件是否已经存在
        /// </summary>
        public bool HasComponent(Type type)
        {
            return this.dictionary.ContainsKey(type);
        }

        /// <summary>
        /// 回收组件
        /// </summary>
        public void Recycle(Component obj)
        {
            Type type = obj.GetType();
            Queue<Component> queue;
            if (!this.dictionary.TryGetValue(type, out queue))
            {
                queue = new Queue<Component>();
                this.dictionary.Add(type, queue);
            }
            queue.Enqueue(obj);
        }
    }
}